﻿@using viBook.Common
@using viBook.Models
@model Chapter
@{
    var totalCommentPage = Math.Ceiling((double)Model.NumberOfComments / Constant.MaximunCommentPerChapter);
    var isShowNextButton = totalCommentPage > 1;
}
<script type="text/javascript">
function Comment() {
    return new Comment(0, "", "", "", 0, false, false, false);
}

function Comment(id, username, content, createdDate, vote, isVotedUp, isVotedDown, isReported) {
    return {
        id: ko.observable(id),
        username: ko.observable(username),
        content: ko.observable(content),
        createdDate: ko.observable(createdDate),
        vote: ko.observable(vote),
        chapterId: ko.observable( @Model.Id ),
        isVotedUp: ko.observable(isVotedUp),
        isVotedDown: ko.observable(isVotedDown),
        isReported: ko.observable(isReported),
        voteUp: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("VoteUp", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.vote(parseInt(currentComment.vote()) + 1);
                            currentComment.isVotedUp(true);
                            currentComment.isVotedDown(false);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        voteDown: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("VoteDown", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.vote(parseInt(currentComment.vote()) - 1);
                            currentComment.isVotedDown(true);
                            currentComment.isVotedUp(false);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        },
        reportContent: function() {
            var currentComment = this;
            $.ajax({
                    url: '@Url.Action("ReportContent", "Comments")',
                    type: 'POST',
                    data: ko.toJSON({ id: this.id }),
                    contentType: 'APPLICATION/JSON',
                    success: function(result) {
                        if (result.isSuccess) {
                            currentComment.isReported(true);
                        } else {
                            alert(result.message);
                        }
                    }
                });
        }
    };
}

function Picture(id, src, tagCollection) {
    return {
        id: id,
        src: ko.observable(src),
        tagCollection: ko.observableArray(tagCollection),
        onRenderTagCompleted: function(elements) {
            var tagIndicator = $(elements)[1];
            var contentDiv = $(elements)[4];
            $(tagIndicator).ready(function() {
                $(tagIndicator).hover(
                    function() {
                        $(contentDiv).toggle(100);
                    }, function() {
                        $(contentDiv).toggle(100);
                    });
            });
        }
    };
}

function Tag(top, left, width, height, content) {
    return {
        top: ko.observable(top+'px'),
        left: ko.observable(left+'px'),
        hoverLeft: ko.observable((left + width)+'px'),
        width:ko.observable(width +'px'),
        height: ko.observable(height+ 'px'),
        content:ko.observable(content)
    };
}

var commentList = [@foreach (ChapterComment item in Model.Comments)
                   {
                        <text>new Comment(@item.Id, "1", "@item.Content", "@item.CreatedDate", "@item.Vote",false,false, false),</text>
                   }];
//TODO: leave this is 1 for now
var pictureList = [
    new Picture(0, "../../Content/nop_598_sleepyfans.01.jpg",
        [
            new Tag(234, 64, 107, 96, "Yeah, I'm coming"),
            new Tag(228, 425, 103, 97, "LUFFY!!"),
            new Tag(381, 54, 106, 102, "This is resukainai, a deserted island to the northwest of the isle of women."),
            new Tag(379, 393, 143, 101, "It's been two years since the ballte between marine headquarters, the shichi bukai, and the whitebeard pirates")
        ])
];
function TagMode(desc, value) {
    return {
        desc: ko.observable(desc),
        value: ko.observable(value)
    };
}
var availableTagModes = [ new TagMode("Normal","TagTemplate"), new TagMode("Hover","TagTemplateHover"),new TagMode("Disable", "TagTemplateDisable")];
var viewmodel = {
    chapterId: @Model.Id ,
    userId: 1,// TODO: Hardcoded for now
    pictureCollection: ko.observableArray(pictureList),
    comment: ko.observable(new Comment()),
    commentCollection: ko.observableArray(commentList),
    commentPageNo: ko.observable(1),
    totalCommentPage: ko.observable(@totalCommentPage),
    isShowPrevBtn: ko.observable(false),
    isShowNextBtn: ko.observable(@isShowNextButton.ToString().ToLower()),
    numberOfComments: ko.observable(@Model.NumberOfComments),
    availableTagModes: ko.observableArray(availableTagModes),
    selectedTagMode: ko.observable(availableTagModes[1]),
    toggleSidebar: function () {
        $('#sideBar').slideToggle('slow');
        $('#button-toggle').toggleClass("active");
    },
    fetchNextCommentPage: function() {
        $.ajax({
                url: '@Url.Action("FetchNextCommentPage", "Comments")',
                type: 'POST',
                data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo()+1}),
                contentType: 'APPLICATION/JSON',
                success: function(result) {
                    if (result.isSuccess) {
                        var listComment = [];
                        $(result.comments).each(function(index, item) {
                            listComment[index]=new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
                        });
                        viewmodel.commentCollection(listComment);
                        viewmodel.commentPageNo(viewmodel.commentPageNo() + 1);
                        viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                        viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                    } else {
                        alert(result.message);
                    }
                }
            });
    },
    fetchPreviousCommentPage: function() {
        $.ajax({
                url: '@Url.Action("FetchNextCommentPage", "Comments")',
                type: 'POST',
                data: ko.toJSON({ chapterId: viewmodel.chapterId, pageNumber: viewmodel.commentPageNo()-1}),
                contentType: 'APPLICATION/JSON',
                success: function(result) {
                    if (result.isSuccess) {
                        var listComment = [];
                        $(result.comments).each(function(index, item) {
                            listComment[index]=new Comment(item.id, item.username, item.content, item.createdDate, item.vote, item.isVotedUp, item.isVotedDown, item.isReported);
                        });
                        viewmodel.commentCollection(listComment);
                        viewmodel.commentPageNo(viewmodel.commentPageNo() - 1);
                        viewmodel.isShowPrevBtn(viewmodel.commentPageNo() > 1);
                        viewmodel.isShowNextBtn(viewmodel.commentPageNo() < viewmodel.totalCommentPage());
                    } else {
                        alert(result.message);
                    }
                }
            });
    },
    postComment: function() {
        $.ajax({
                url: '@Url.Action("Create", "Comments")',
                type: 'POST',
                data: ko.toJSON({ userId: viewmodel.userId, content: viewmodel.comment().content(), chapterId: viewmodel.chapterId }),
                contentType: 'APPLICATION/JSON',
                success: function(result) {
                    if (result.isSuccess) {
                        var addedComment = new Comment(
                            parseInt(result.id),
                            viewmodel.comment().username(),
                            viewmodel.comment().content(),
                            viewmodel.comment().createdDate(),
                            viewmodel.comment().vote(),
                            viewmodel.comment().isVotedUp(),
                            viewmodel.comment().isVotedUp(),
                            viewmodel.comment().isReported());
                        viewmodel.commentCollection.unshift(addedComment);
                        viewmodel.comment(new Comment());
                    } else {
                        alert(result.message);
                    }
                }
            });
    },
    cancelPostComment: function() {
        viewmodel.comment(new Comment());
    }
};
//viewmodel.isShowSidebar.subscribe(function() {
//    $('#sideBar').toggle(0);
//});
ko.applyBindings(viewmodel);


//var distanceFromTop = $('#sideBar').offset().top - parseFloat($('#sideBar').css('marginTop').replace( /auto/ , 0));
//$(window).scroll(function() {
//    var y = $(this).scrollTop();
//    if (y >= distanceFromTop) {
//        $('#sideBar').addClass('fixed');
//    } else {
//        $('#sideBar').removeClass('fixed');
//    }
//});
</script>
